'use client';

import { Button, Card, Form, Input, Modal, Table } from '@arco-design/web-react';
import { useLocalStorageState } from 'ahooks';
import React, { useState } from 'react';
import { MODELS_STORAGE_KEY } from '../../../constants/models';
import { extractStrictJSON } from '../../../utils';

export interface Model {
  id: string;
  name: string;
  baseUrl: string;
  apiKey: string;
  model: string;
  parameters?: Record<string, any>;
}

export interface ModelFormValues extends Omit<Model, 'parameters'> {
  parameters?: string;
}


export default function ModelManagerPage() {
  const [models, setModels] = useLocalStorageState<Model[]>(MODELS_STORAGE_KEY, { defaultValue: [] });


  const [visible, setVisible] = useState(false);
  const [currentModel, setCurrentModel] = useState<Model | null>(null);
  const [form] = Form.useForm<ModelFormValues>();



  const handleSubmit = (values: ModelFormValues) => {

    // 转换为 Model 类型
    const modelValues: Omit<Model, 'id'> = {
      ...values,
      parameters: values.parameters ? extractStrictJSON(values.parameters) : undefined,
    };

    let newModels: Model[];
    if (currentModel) {
      newModels = models.map(m =>
        m.id === currentModel.id ? { ...modelValues, id: currentModel.id } : m
      );
    } else {
      newModels = [...models, { ...modelValues, id: Date.now().toString() }];
    }
    setModels(newModels);
    setVisible(false);
    form.resetFields();
  };

  const handleDelete = (id: string) => {
    const newModels = models.filter(m => m.id !== id);
    setModels(newModels);
  };

  return (
    <Card title="模型管理" className="mb-4">
      <Button 
        type="primary" 
        onClick={() => {
          setCurrentModel(null);
          setVisible(true);
        }}
      >
        添加模型
      </Button>

      <Table
        className="mt-4"
        data={models}
        key="name"
        columns={[
          { title: '名称', dataIndex: 'name' },
          { title: '模型', dataIndex: 'model' },
          { title: 'Base URL', dataIndex: 'baseUrl', ellipsis: true },
          {
            title: '参数',
            dataIndex: 'parameters',
            render: (parameters: Record<string, any> | undefined) => {
              if (!parameters) return '-';
              return JSON.stringify(parameters);
            }
          },
          {
            title: '操作',
            render: (_, record) => (
              <div className="space-x-2">
                <Button 
                  size="mini" 
                  onClick={() => {
                    setCurrentModel(record);
                    // 将参数对象转换为字符串以在表单中显示
                    const formValues = {
                      ...record,
                      parameters: record.parameters ? JSON.stringify(record.parameters, null, 2) : ''
                    };
                    form.setFieldsValue(formValues);
                    setVisible(true);
                  }}
                >
                  编辑
                </Button>
                <Button 
                  size="mini" 
                  status="danger"
                  onClick={() => handleDelete(record.id)}
                >
                  删除
                </Button>
              </div>
            ),
          },
        ]}
      />

      <Modal
        title={currentModel ? '编辑模型' : '添加模型'}
        visible={visible}
        onCancel={() => {
          setVisible(false);
          form.resetFields();
        }}
        onOk={() => form.submit()}
      >
        <Form form={form} onSubmit={handleSubmit}>
          <Form.Item label="名称" field="name" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item label="Base URL" field="baseUrl" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item label="API Key" field="apiKey" rules={[{ required: true }]}>
            <Input.Password />
          </Form.Item>
          <Form.Item label="模型" field="model" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item label="参数" field="parameters">
            <Input.TextArea placeholder="请输入JSON格式的参数，例如：{'temperature': 0.7, 'max_tokens': 100}" />
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  );
}